#!/usr/bin/python
'''
Main Controller
'''

import bottle
from bottle import template
from beaker.middleware import SessionMiddleware
from plugins.cork import Cork
from plugins.cork.backends import MongoDBBackend
import logging

logging.basicConfig(format='localhost - - [%(asctime)s] %(message)s', level=logging.DEBUG)
log = logging.getLogger(__name__)
bottle.debug(True)

# Create a mongoDB backend
backend = MongoDBBackend(db_name='licitaDB')

# Initialize Cork with mongoDB support
authCork = Cork(backend=backend, email_sender='roberto.raguze@gmail.com', smtp_url='smtp://smtp.magnet.ie')

# alias the authorization decorator with defaults
authorize = authCork.make_auth_decorator(fail_redirect="/login", role="visitor")

import datetime
app = bottle.app()
session_opts = {
    'session.cookie_expires': True,
    'session.encrypt_key': '123456789',
    'session.httponly': True,
    'session.timeout': 3600 * 24,  # 1 day
    'session.type': 'cookie',
    'session.validate_key': True,
}
app = application = SessionMiddleware(app, session_opts)

def postd():
    return bottle.request.forms

def post_get(name, default=''):
    return bottle.request.POST.get(name, default).strip()

#====================================================================================
# Login
#====================================================================================
@bottle.get('/login')
def login_form():
    """Serve login form"""
    pageToBase = 'login.tpl'
    return template('views/login')

@bottle.post('/login')
def login():
    """Authenticate users"""
    username = post_get('username')
    password = post_get('userpassword')
    authCork.login(username, password, success_redirect='/', fail_redirect='/login')

#====================================================================================
# Register
#====================================================================================
@bottle.get('/register')
def register_form():
    """Serve register form"""
    pageToBase = 'register.tpl'
    return template('views/register')

@bottle.post('/register')
def register():
    """Register new users"""
    username = post_get('username')
    useremail = post_get('useremail')
    """Send out registration email"""
    authCork.register(username, "", useremail)
    return 'Please check your mailbox.'

#====================================================================================
# Index
#====================================================================================
@bottle.route('/')
@authorize()
def show_index():
    '''
    The front "index" page
    Only authenticated users can proceed
    '''
    pageToBase = 'index.tpl'
    return template('views/index')


@bottle.route('/static/<filename:path>')
def static(filename):
    '''
    Serve static files
    '''
    return bottle.static_file(filename, root='{}/static'.format(conf.get('bottle', 'root_path')))


@bottle.route('/page/<page_name>')
def show_page(page_name):
    '''
    Return a page that has been rendered using a template
    '''
    output = template('views/page', name=page_name)
    return output


class StripPathMiddleware(object):
    '''
    Get that slash out of the request
    '''
    def __init__(self, a):
        self.a = a
    def __call__(self, e, h):
        e['PATH_INFO'] = e['PATH_INFO'].rstrip('/')
        return self.a(e, h)

if __name__ == '__main__':
    bottle.run(app=StripPathMiddleware(app),
        server='wsgiref',
        host='0.0.0.0',
        port=8080)